package com.app.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeUtil;
import com.app.common.CalculateDistance;
import com.app.common.SystemConstant;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.ActivityService;
import com.app.service.IClassificationSubclassService;
import com.app.service.IGroupBuyingCategoryService;
import com.app.utils.AliyunOSSUtils;
import com.app.utils.CommonHelp;
import com.app.vo.ActivityVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 活动
 *
 * @author 16693103420
 * @since 2024-01-22
 */
@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, ActivityModel> implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;
    @Autowired
    private BusinessMapper businessMapper;
    @Autowired
    private BusinessActivityMapper businessActivityMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private VoucherRecordMapper voucherRecordMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private MessageBoxMapper messageBoxMapper;
    @Autowired
    private IClassificationSubclassService classificationSubclassService;
    @Autowired
    private IGroupBuyingCategoryService groupBuyingCategoryService;

    //查询平台所有的活动列表
    @Override
    public ActivityVo getActivityList(Integer page, Integer limit) {
        Page<ActivityModel> page1 = new Page<>(page, limit);
        QueryWrapper<ActivityModel> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        Page<ActivityModel> activityPage = activityMapper.selectPage(page1, qw);

        List<ActivityModel> activityList = activityPage.getRecords();

        long count = activityPage.getTotal();
        ActivityVo activityVo = new ActivityVo();
        activityVo.setList(activityList);
        activityVo.setCount((int) count);
        return activityVo;

    }


    //定时器，每天凌晨0点执行
    //领取的产品只限当天使用，过期作废
    @Scheduled(cron = "0 0 0 * * ?")
    @Transactional
    public void updateOrderToday(){
        System.err.println("-------免费订单过期取消轮询开始-------");
        orderMapper.updateOrderToday();
        System.err.println("-------免费订单过期取消轮询结束-------");

    }

    //查询此商家待添加活动
    @Override
    public ActivityVo getActivityByBusiness(Integer page, Integer limit, Integer businessId) {
        Page<ActivityModel> page1 = new Page<>(page, limit);
        QueryWrapper<ActivityModel> qw = new QueryWrapper<>();
        qw.orderByDesc("create_time");
        qw.eq("business_id", businessId);
        Page<ActivityModel> activityPage = activityMapper.selectPage(page1, qw);

        List<ActivityModel> activityList = activityPage.getRecords();
        for (ActivityModel model : activityList) {
            if (model.getIsPick() != null) {
                if (model.getIsPick() == 1) {
                    model.setPick("是");
                } else {
                    model.setPick("否");
                }
            }
        }
        long count = activityPage.getTotal();
        ActivityVo activityVo = new ActivityVo();
        activityVo.setList(activityList);
        activityVo.setCount((int) count);
        return activityVo;
    }
    @Autowired
    private AliyunOSSUtils aliyunOSSUtils;
    @Override
    public void buyNowActivity(ActivityModel activity, UserModel user) {
        //更新库存
        ActivityModel activityModel = activityMapper.selectById(activity.getId());
        if (activityModel!=null){
            activityModel.setNumber(activityModel.getNumber() - 1);
            activityModel.setId(activity.getId());
            activityMapper.updateById(activityModel);
        }
        //生成益联券订单
        BusinessModel businessModel = businessMapper.selectById(activity.getBusinessId());
        OrderModel orderModel = new OrderModel();
        orderModel.setBusinessName(businessModel.getBusinessName());
        orderModel.setActivityName(activity.getActivityName());
        orderModel.setActivityCover(activity.getCover());
        orderModel.setVoucher(activity.getPrice());
        String orderId = IdUtil.fastSimpleUUID();
        orderModel.setOrderId(orderId);
        orderModel.setCreateTime(CommonHelp.getNowTimestamp());
        orderModel.setBusinessId(activity.getBusinessId());
        orderModel.setUserId(user.getId());
        orderModel.setAreaId(user.getAreaId());
        orderModel.setCityId(user.getCityId());
        orderModel.setActivityId(activity.getId());
        String verificationCodePath = System.getProperty("user.dir") + File.separator + "file" + File.separator + orderId + ".png";
        QrCodeUtil.generate(orderId, 300, 300, FileUtil.file(verificationCodePath));
        String fileURL = SystemConstant.DEFAULT_PDF_SERVICE_URL + orderId + ".png";
        try{
            aliyunOSSUtils.objectStorageUploadFile(fileURL,FileUtil.getInputStream(verificationCodePath));
        }catch (Exception e)
        {

        }
        orderModel.setVerificationCode(fileURL);
        orderMapper.insert(orderModel);
        //免费活动不扣
        if (1 != activity.getClassification()){
            //将用户益联券扣除
            user.setVoucher(user.getVoucher() - activity.getPrice());
            userMapper.updateById(user);
            //生成用户益联券记录
            VoucherRecordModel voucherRecordModel = new VoucherRecordModel();
            voucherRecordModel.setName(activity.getActivityName());
            voucherRecordModel.setTypeName("活动抢购");
            voucherRecordModel.setBusinessId(orderModel.getBusinessId());
            String amountVoucher = "-" + activity.getPrice() + "券";
            voucherRecordModel.setVoucher(amountVoucher);
            voucherRecordModel.setUserId(user.getId());
            voucherRecordModel.setCreateTime(CommonHelp.getNowTimestamp());
            voucherRecordModel.setOrderId(orderModel.getOrderId());
            voucherRecordModel.setVoucherType(0);
            voucherRecordModel.setVoucherAmount(-activity.getPrice());
            voucherRecordModel.setWriteOff(2);
            voucherRecordMapper.insert(voucherRecordModel);
        }
        //消息盒子记录数据
        MessageBoxModel messageBoxModel = new MessageBoxModel();
        messageBoxModel.setUserId(user.getId());
        messageBoxModel.setQuiltUserId(user.getId());
        messageBoxModel.setTypeName("消费通知");
        messageBoxModel.setVoucher(activity.getPrice());
        messageBoxModel.setNotes("活动【" + activity.getActivityName() + "】抢购成功");
        messageBoxModel.setCreateTime(CommonHelp.getNowTimestamp());
        messageBoxModel.setOrderSn(orderModel.getOrderId());
        messageBoxMapper.insert(messageBoxModel);
    }

    @Override
    public ActivityModel getActivityById(Integer id, Double longitude, Double latitude) {
        ActivityModel activity = activityMapper.selectById(id);

        String groupBuyingId = activity.getGroupBuyingId();
        List<Integer> groupBuyingIdList =new ArrayList<>();
        if (groupBuyingId!= null) {
            groupBuyingIdList = Arrays.stream(groupBuyingId.split(","))
                    .map(Integer::valueOf)
                    .collect(Collectors.toList());

            QueryWrapper<GroupBuyingCategory> groupBuyingCategoryQueryWrapper = new QueryWrapper<>();
            groupBuyingCategoryQueryWrapper.in("id", groupBuyingIdList);
            groupBuyingCategoryQueryWrapper.eq("status", 1);
            groupBuyingCategoryQueryWrapper.orderByDesc("sort");
            groupBuyingCategoryQueryWrapper.orderByDesc("create_time");
            List<GroupBuyingCategory> groupBuyingCategoryList = groupBuyingCategoryService.list(groupBuyingCategoryQueryWrapper);
            for (GroupBuyingCategory groupBuyingCategory : groupBuyingCategoryList) {
                QueryWrapper<ClassificationSubclass> classificationSubclassQueryWrapper = new QueryWrapper<>();
                classificationSubclassQueryWrapper.eq("category_id", groupBuyingCategory.getId());
                classificationSubclassQueryWrapper.eq("status", 1);
                classificationSubclassQueryWrapper.orderByDesc("sort");
                classificationSubclassQueryWrapper.orderByDesc("create_time");
                List<ClassificationSubclass> classificationSubclassList = classificationSubclassService.list(classificationSubclassQueryWrapper);
                groupBuyingCategory.setClassificationSubclasses(classificationSubclassList);
            }
            activity.setGroupBuyingCategoryList(groupBuyingCategoryList);
        }

        //查看适用门店
        if(StrUtil.isNotBlank(activity.getBusinessIds()))
        {
            List<String> businessIds= Arrays.asList(activity.getBusinessIds().split(","));
            Integer status=1;
            Integer businessStatus=1;
            List<BusinessModel> businessIdList=businessMapper.queryListByBusinessIds(status,
                    businessStatus,
                    businessIds,
                    longitude,
                    latitude);
            activity.setBusinessList(businessIdList);
        }

        Long count = activity.getViewCount() == null ? 1 : activity.getViewCount();
        count++;
        activity.setViewCount(count);
        activityMapper.updateById(activity);

        return activity;
    }

    @Override
    public Integer getViewCount(Integer id) {
        return activityMapper.getViewCount(id);
    }
}
